/**
 * Created by Administrator on 2017/7/3.
 */

let rechargeDao = require('../mysql/rechargeDao.js');
let firstPaidDao = require('../mysql/firstPaidDao.js');
let bluedSDK = require('../util/bluedSDK.js');
let weixinSDK = require('../util/weixinSDK.js');
let msg = require('../util/msg.js');
let variable = require('../data/variable.js');
let rpc = require('../util/rpc.js'); 
let gameData = require('../util/gameData.js');
let publicDao = require('../mysql/publicDao.js');

let call = module.exports;

module.exports = recharge;

function recharge(userId, openid, cid, uuid, goodsId) {
    this._userId = userId;
    this._openId = openid;
    this._accessToken = null;
    this._cid = cid;
    this._uuid = uuid;
    this._goodsId = goodsId;
}
recharge.goods = function (userId, cid, uuid, platform) {
    if (gameData.d.config.recharge) {
        let noDouble = {};
        if (gameData.d.activity.firstPaid && gameData.d.activity.firstPaid.state === 1) {
            publicDao.init().table('firstpaid').wheres('userId', '=', userId).get(function (err, res) {
                if (res.length > 0) {
                    for (let i in res) {
                        noDouble[res[i].goodsId] = true;
                    }
                }
                recharge.goodsList(userId, cid, uuid, platform, noDouble);
            });
        } else {
            for (let i in gameData.d.goods) {
                noDouble[gameData.d.goods[i].goods_id] = true;
            }
            recharge.goodsList(userId, cid, uuid, platform, noDouble);
        }
    }
};
recharge.goodsList = function (userId, cid, uuid, platform, noDouble) {
    let goods = [];
    for (let i in gameData.d.goods) {
        if (!gameData.d.config.touristLogin && gameData.d.goods[i].platform != platform) {
            continue;
        }
        goods.push({
            'id': gameData.d.goods[i].goods_id,
            'name': gameData.d.goods[i].name,
            'coin': gameData.d.goods[i].coin,
            'type': gameData.d.goods[i].type,
            'price': gameData.d.goods[i].beans,
            'give': gameData.d.goods[i].give,
            'hot': gameData.d.goods[i].hot,
            'double': noDouble[i] ? false : true
        });
    }
    msg.send(cid, uuid, 'funcGoods', goods);
};

recharge.prototype.run = function () {
    this.makeOrders(this._openId);
};

recharge.prototype.makeOrders = function (openid) {
    let _this = this;
    //先查找有没有同商品未处理的
    let rechargeModel0 = new rechargeDao(); 
    console.log("makeOrders",_this._userId,_this._goodsId); 
    rechargeModel0.inGoodIdNotOk(_this._userId,_this._goodsId,function (err, res){
        console.log(JSON.stringify(res));
        if (err == null && res!=null) {
            //请求微信订单 
            var qdata = {
                // transaction_id:transaction_id,
                out_trade_no : res.res.id
            };  
            weixinSDK.orderQuery(qdata,function(err,res){
                if(err!=null){
                    msg.send(_this._cid, _this._uuid, 'error', {'api': 'funcRecharge', 'code': 10066});
                    return;
                }   
                console.log(JSON.stringify(res));
                if(res.return_code=="SUCCESS"){
                    //充值成功回调接口 
                    rpc.dc.send('payCallback',{'ordersId':res.res.id,'userId':_this._userId}); 
                }else{
                    if(res.return_code=="NOTPAY"){
                        //关闭微信订单
                        weixinSDK.orderClose(qdata,function(err,res){
                            
                        });
                    }   
                    console.log("系统关闭订单")
                    rpc.dc.send('closeOrder',{'ordersId':rechargeModel0.id});
                    //系统关闭订单
                }
            });  
        }    
    }); 
    
    //重新下订单
    let rechargeModel = new rechargeDao(); 
    rechargeModel.set('userId', _this._userId);
    rechargeModel.set('goodsId', _this._goodsId);
    rechargeModel.set('createTime', new Date().Format("yyyy-MM-dd hh:mm:ss"));
    rechargeModel.set('status', 0);
    rechargeModel.set('beans', gameData.d.goods[_this._goodsId].beans);
    rechargeModel.save(function (err, res) {
        if (err != null) {
            msg.send(_this._cid, _this._uuid, 'error', {'api': 'funcRecharge', 'code': 10066});
            return false;
        }   
        _this.weixinOrder(openid,res.res.insertId)
    });
    
};

recharge.prototype.weixinOrder = function (openid,ordersId) {

    let _this = this;
    
    var good = gameData.d.goods[_this._goodsId];
    
    var ip = _this._cid
    if (ip.substr(0, 7) == "::ffff:") {
        ip = ip.substr(7); 
        ip = "127.0.0.1";
    }   
    
    let body = {}; 
    body.attach = ""+_this._userId;
    body.body = good.name; 
    body.openid = openid;
    body.out_trade_no = ordersId;
    body.spbill_create_ip = ip;
    body.total_fee = good.beans;
    
    weixinSDK.getOrder( body , function(error,res){
        if(error!=null){
            msg.send(_this._cid, _this._uuid, 'error', {'api': 'funcRecharge', 'code': 10070});
        }else{
            console.log(res);
            //更新订单记录
            // pay.updateTransaction(transaction_id,) 

            msg.send(_this._cid, _this._uuid, 'funcRecharge', {'url': res});
        }
    });
    
};

recharge.prototype.makeUrl = function (accessToken, ordersId) {
    let body = {};
    body.ordersId = ordersId;
    body.userId = this._userId;
    let bodyString = encodeURIComponent(JSON.stringify(body));
    let url = bluedSDK.payUrl(accessToken, this._goodsId, bodyString); 
    msg.send(this._cid, this._uuid, 'funcRecharge', {'url': url});
};